from urllib.request import urlopen, Request
from http.client import HTTPResponse
url = 'http://www.bing.com'

ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 ' \
     'Safari/537.36 '
req = Request(url, headers={
    'User-agent': ua
})
#req.add_header('User-agent', ua)
# get 请求
response = urlopen(req)
print(response.closed)

with response:
    print(type(response))
    print(response.status)
    print(response._method)
    print(response.info())  # headers
    print(response.read())

print(req.get_header('User-agent'))
print(response.closed)